
package com.idealighter.game.games.sirenniuniu.handler;

import com.idealighter.game.core.annotation.ResMsgHandler;
import com.idealighter.game.dictionary.domain.SirenniuniuRoomDomain;
import com.idealighter.game.gamehall.dto.MemInfo;
import com.idealighter.game.games.common.NiuNiuCardsType;
import com.idealighter.game.games.sirenniuniu.SiRenNiuNiuPlayer;
import com.idealighter.game.games.sirenniuniu.message.ReqReadyMsg;
import com.idealighter.game.message.ModuleMsgIdConstant;
import com.idealighter.game.message.core.ResMessage;
import com.idealighter.game.robot.common.PlayerPosition;
import com.idealighter.game.robot.core.Player;
import com.idealighter.game.robot.handler.ResMessageHandler;
import com.idealighter.utils.code.RandCodeUtil;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ResMsgHandler(ModuleMsgIdConstant.SiRenNiuNiu.RES_ENTER_TABLE)
public class ResEnterTableHandler implements ResMessageHandler {

  private static final Logger LOG = LoggerFactory.getLogger(ResEnterTableHandler.class);

  @Override
  public void action(Player player, ResMessage message) {
    // ResEnterTableMsg msg = (ResEnterTableMsg)message;
    player.position = PlayerPosition.TABLE;
    LOG.info("[四人牛牛]玩家[{}][{}]进入桌子[{}]成功", player.userName, player.playerId,
        player.table(player.playerId).getId());

    // 随机延时3到5秒兑换筹码和准备
    player.schedule(() -> {
      SirenniuniuRoomDomain roomDomain = ((SiRenNiuNiuPlayer) player).roomDomain;
      MemInfo member = player.member(player.playerId);

      int maxMultiple = NiuNiuCardsType.getMaxMultiple();
      int leftPersonNum = roomDomain.getChair() - 1;
      long minChips =
          roomDomain.getBaseBet() * roomDomain.getMinBetMultiple() * maxMultiple * leftPersonNum;

      if (player.playerInfo.getGold() <= 0) {
        if (member.getChips() < minChips) {
          player.delayLogout();
        }
      } else if (member.getChips() > minChips) {
        long chips = member.getChips() + convertChip(roomDomain, member.getGold());
        if (chips > minChips) {
          player.sendMsg(new ReqReadyMsg());
        }

      }
    }, RandCodeUtil.random(3, 5), TimeUnit.SECONDS);
  }

  /**
   * 金币转筹码.
   * 
   * @param roomDomain .
   * @param gold .
   * @return .
   */
  public long convertChip(SirenniuniuRoomDomain roomDomain, long gold) {
    return gold * roomDomain.getProportionChips() / roomDomain.getProportionGold();
  }
}
